package br.com.management.mentor.view;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.management.mentor.controller.auth.UserController;
import br.com.management.mentor.model.entities.auth.User;
import br.com.management.mentor.view.core.View;
import br.com.management.mentor.view.events.LoggedEvent;

public class LoginView extends View {

	private Composite parent;
	
	@Autowired
	private UserController userController;
	
	@Override
	public void build( Composite parent ) {
		this.parent = parent;
		
		Label userLabel = new Label( parent , SWT.CENTER );
		userLabel.setText( "Usuário" );
		userLabel.setBounds( parent.getClientArea() );
		
		final Text userText = new Text( parent , SWT.CENTER );
		
		Label passwordLabel = new Label( parent , SWT.LEFT );
		passwordLabel.setText( "Senha" );
		passwordLabel.setBounds( parent.getClientArea() );
		
		final Text passwordText = new Text( parent , SWT.LEFT | SWT.PASSWORD );
		
		Button loginBtn = new Button( parent , SWT.PUSH );
		loginBtn.setText( "Entrar" );

		loginBtn.addSelectionListener( new SelectionListener() {
			
			@Override
			public void widgetSelected( SelectionEvent e ) {
				String username = userText.getText();
				String password = passwordText.getText();
				
				User user = userController.login( username , password );
				
				setChanged();
				notifyObservers( new LoggedEvent( user ) );
			}
			
			@Override
			public void widgetDefaultSelected( SelectionEvent e ) { }
			
		} );
	}

	@Override
	public Shell getParent() {
		return parent.getShell();
	}

}